<?php
/**
 * Created by PhpStorm.
 * User: ADMIN
 * Date: 2021/6/27
 * Time: 7:07
 */

namespace app\adminapi\validate;

use app\common\model\ChangeFunction;

class ChangeFunctionUpdate extends Base
{
    protected $rule = [
        'id' => 'require|integer|min:1|dataExists',
        'change_category_ids' => 'require|changeCategoryExists',
        'name' => 'require|nameUnique',
        'document_str' => 'require|templateExists',
        'status' => 'require|checkStatus',
    ];

    protected $message = [
        'id.dataExists' => '数据不存在',

        'change_category_ids.changeCategoryExists' => '有部分变更类别不存在',

        'name.nameUnique' => '变更类别名唯一',

        'document_str.templateExists' => '有部分模板不存在',

        'status.checkStatus' => 'status值只能为0或1',
    ];

    /**
     * 数据是否存在
     * @param $value
     * @return bool
     * @throws \think\Exception
     */
    protected function dataExists($value)
    {
        if(!db('change_function')->where("id={$value}")->count()) return false;
        return true;
    }

    /**
     * 变更类别是否存在
     * @param $value
     * @return bool
     * @throws \think\Exception
     */
    protected function changeCategoryExists($value)
    {
        if($arr = explode(',', $value)){
            foreach ($arr as $v) {
                if (!db('change_category')->where("id={$v}")->count()) return false;
            }
        }
        return true;
    }

    /**
     * 变更功能名唯一
     * @param $value
     * @return bool
     * @throws \think\Exception
     */
    protected function nameUnique($value, $rule, $data)
    {
        if (db('change_function')->where("name='{$value}' and id!={$data['id']}")->count()) return false;
        return true;
    }

    /**
     * 模板及排序判断
     * @param $value
     * @return bool
     * @throws \think\Exception
     */
    protected function templateExists ($value) {
        if(!$arr = json_decode($value, true)) return false;
        foreach ($arr as $v) {
            if(!(is_int($v['id']) && is_int($v['sort']))) return false;
            if (!db('template')->where("id={$v['id']}")->count()) return false;
        }
        return true;
    }

    /**
     * 状态验证
     * @param $value
     * @return bool
     */
    protected function checkStatus($value)
    {
        if (!ChangeFunction::getStatusText($value)) return false;
        return true;
    }

}